//
//  EDPTGameDetailViewController.m
//  EDF
//
//  Created by 微笑吧阳光 on 2019/8/8.
//  Copyright © 2019 p. All rights reserved.
//

#import "EDPTGameDetailViewController.h"
#import <WebKit/WebKit.h>
#import <AVFoundation/AVFoundation.h>
#import "UIDevice+TFDevice.h"
#import "MBProgressHUD.h"
#import "CCZSpreadButton.h"
#import "EDWalletCenterViewController.h"

@interface EDPTGameDetailViewController ()
<UIWebViewDelegate,UIGestureRecognizerDelegate,WKScriptMessageHandler,CCZSpreadButtonDelegate>
@property (nonatomic, strong) CCZSpreadButton *com;
@property (nonatomic, strong) UIWebView *webView;
@property (nonatomic, strong) UIBarButtonItem *backBarButtonItem;
@property (nonatomic, strong) UIBarButtonItem *closeBarButtonItem;
@property (nonatomic, strong) id <UIGestureRecognizerDelegate>delegate;
@property (nonatomic, strong) UIRefreshControl *refreshControl;
@property (nonatomic, strong) UIProgressView *loadingProgressView;
@property (nonatomic, strong) UIButton *reloadButton;
@property (nonatomic, strong) UIButton *blakButton;
@property (nonatomic, strong) NSTimer *fakeProgressTimer;
@property (nonatomic, assign) BOOL uiWebViewIsLoading;
@property (nonatomic, strong) NSURL *uiWebViewCurrentURL;
@end

@implementation EDPTGameDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createWebView];
    [self createNaviItem];
    [self loadRequest];
    //允许转成横屏
    [self allowRotation:_allowRotation];
}
#pragma mark - Fake Progress Bar Control (UIWebView)

- (void)fakeProgressViewStartLoading {
    [self.loadingProgressView setProgress:0.0f animated:NO];
    [self.loadingProgressView setAlpha:1.0f];
    
    if(!self.fakeProgressTimer) {
        self.fakeProgressTimer = [NSTimer scheduledTimerWithTimeInterval:1.0f/60.0f target:self selector:@selector(fakeProgressTimerDidFire:) userInfo:nil repeats:YES];
    }
}

- (void)fakeProgressBarStopLoading {
    if(self.fakeProgressTimer) {
        [self.fakeProgressTimer invalidate];
    }
    
    if(self.loadingProgressView) {
        [self.loadingProgressView setProgress:1.0f animated:YES];
        [UIView animateWithDuration:0.3f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
            [self.loadingProgressView setAlpha:0.0f];
        } completion:^(BOOL finished) {
            [self.loadingProgressView setProgress:0.0f animated:NO];
        }];
    }
}

- (void)fakeProgressTimerDidFire:(id)sender {
    CGFloat increment = 0.005/(self.loadingProgressView.progress + 0.2);
    if([self.webView isLoading]) {
        CGFloat progress = (self.loadingProgressView.progress < 0.75f) ? self.loadingProgressView.progress + increment : self.loadingProgressView.progress + 0.0005;
        if(self.loadingProgressView.progress < 0.95) {
            [self.loadingProgressView setProgress:progress animated:YES];
        }
    }
}

//横屏竖屏
- (void)allowRotation:(BOOL)allowRotation
{
    AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    appDelegate.allowRotation = allowRotation;
    if (allowRotation) {
        //调用转屏代码
        [UIDevice switchNewOrientation:UIInterfaceOrientationLandscapeRight];
        //self.webView.frame = CGRectMake(0, 0, UIScreenWidth,UIScreenHeight);
        _webView.frame = CGRectMake(0, 0, UIScreenWidth, UIScreenHeight);
        _loadingProgressView.frame = CGRectMake(0, 0, UIScreenWidth, 2);
        self.com.frame = CGRectMake(UIScreenWidth-100, UIScreenHeight-100, 50, 50);
    }else
    {
        [UIDevice switchNewOrientation:UIInterfaceOrientationPortrait];
        _webView.frame = CGRectMake(0, 0, UIScreenWidth, UIScreenHeight);
        _loadingProgressView.frame = CGRectMake(0, 0, UIScreenWidth, 2);
       self.com.frame = CGRectMake(UIScreenWidth-100, UIScreenHeight-100, 50, 50);
    }
    
}
#pragma mark 版本适配
- (void)createWebView {
    //    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.view addSubview:self.reloadButton];
   
    [self.view addSubview:self.webView];
    [self.view addSubview:self.loadingProgressView];
    
    CCZSpreadButton *com  = [[CCZSpreadButton alloc] initWithFrame:CGRectMake(200, 200, 50, 50)];
    com.itemsNum = 4;
    com.autoAdjustToFitSubItemsPosition = YES;
    com.spreadButtonOpenViscousity = NO;
    com.wannaToScaleSpreadButtonEffect = NO;
    com.backgroundColor = [UIColor clearColor];
    //com.radius
    com.normalImage = [UIImage imageNamed:@"menu_Open"];
    com.selImage = [UIImage imageNamed:@"menu_Close"];
    com.images = @[@"menu_back",@"menu_Refush",@"menu_cunkuan",@"menu_Zhuan"];
    [com spreadButtonDidClickItemAtIndex:^(NSUInteger index) {
        NSLog(@"%ld",index);
        switch (index) {
            case 0:
            {
               // [self back:nil];
                //允许转成横屏
                dispatch_async(dispatch_get_main_queue(), ^{
                   [self allowRotation:NO];
                   [self.navigationController popViewControllerAnimated:YES];
                });

            }
                break;
            case 1:
            {
                NSHTTPCookie*cookie;
                NSHTTPCookieStorage*storage =[NSHTTPCookieStorage sharedHTTPCookieStorage];for(cookie in[storage cookies]){      [storage deleteCookie:cookie];}
              [self loadRequest];
            }
                break;
            case 2:
            {
                 EDWalletCenterViewController *vc2 = [[EDWalletCenterViewController alloc] init];
                if (_allowRotation==YES) {
                    AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
                    appDelegate.allowRotation = NO;//关闭横屏仅允许竖屏
                    [self allowRotation:NO];
                }
                vc2.title = @"钱包";
                vc2.selectIndex =0;
                 [AppDelegate shareAppdelegate].index = 0;
                vc2.isWebGo = YES;
                [self.navigationController pushViewController:vc2 animated:YES];
            }
                break;
            case 3:
            {
                EDWalletCenterViewController *vc2 = [[EDWalletCenterViewController alloc] init];
                if (_allowRotation==YES) {
                    AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
                    appDelegate.allowRotation = NO;//关闭横屏仅允许竖屏
                    [self allowRotation:NO];
                }
                vc2.title = @"钱包";
                vc2.isWebGo = YES;
                vc2.selectIndex =1;
                [AppDelegate shareAppdelegate].index = 1;
                [self.navigationController pushViewController:vc2 animated:YES];
            }
                break;
                
            default:
                break;
        }
    }];
    self.com = com;
     [self.view addSubview:self.com];
}

- (UIWebView*)webView {
    if (!_webView) {
        _webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
        _webView.delegate = self;
        if ([[[UIDevice currentDevice]systemVersion]floatValue] >= 10.0 ) {
           // _webView.scrollView.refreshControl = self.refreshControl;
        }
    }
    return _webView;
}

- (UIProgressView*)loadingProgressView {
    if (!_loadingProgressView) {
        _loadingProgressView = [[UIProgressView alloc]initWithFrame:CGRectMake(0, 0 , self.view.bounds.size.width, 2)];
        _loadingProgressView.progressTintColor = TABTITLECOLOR;
        _loadingProgressView.backgroundColor = CLEARCOLOR;
    }
    return _loadingProgressView;
}

- (UIRefreshControl*)refreshControl {
    if (!_refreshControl) {
        _refreshControl = [[UIRefreshControl alloc]init];
        [_refreshControl addTarget:self action:@selector(webViewReload) forControlEvents:UIControlEventValueChanged];
    }
    return _refreshControl;
}

- (void)webViewReload {
    [_webView reload];
}

- (UIButton*)reloadButton {
    if (!_reloadButton) {
        _reloadButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _reloadButton.frame = CGRectMake(0, 0, 150, 150);
        _reloadButton.center = self.view.center;
        _reloadButton.layer.cornerRadius = 75.0;
        [_reloadButton setBackgroundImage:[UIImage imageNamed:@"placeholder"] forState:UIControlStateNormal];
        [_reloadButton setTitle:@"" forState:UIControlStateNormal];
        
        [_reloadButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        [_reloadButton setTitleEdgeInsets:UIEdgeInsetsMake(200, -50, 0, -50)];
        _reloadButton.titleLabel.numberOfLines = 0;
        _reloadButton.titleLabel.textAlignment = NSTextAlignmentCenter;
        CGRect rect = _reloadButton.frame;
        rect.origin.y -= 100;
        _reloadButton.frame = rect;
        _reloadButton.enabled = NO;
    }
    return _reloadButton;
}
- (void)createNaviItem {
    [self showLeftBarButtonItem];
}

- (void)showLeftBarButtonItem {
    if ([_webView canGoBack]) {
        [self.view addSubview:self.blakButton];
    } else {

            [self.view addSubview:self.blakButton];
            _blakButton.transform=CGAffineTransformMakeRotation(M_PI);

    }
}
#pragma mark 导航按钮
- (UIButton *)blakButton
{
    if (!_blakButton) {
        
        //        //回到上一页
        //       _blakButton = [UIButton buttonWithType:UIButtonTypeCustom];
        //        _blakButton.frame = CGRectMake(0, 0, 46, 100);
        //        _blakButton.contentEdgeInsets = UIEdgeInsetsMake(0, -15, 0, 0);
        //        [_blakButton setImage:[UIImage imageNamed:@"return"] forState:0];
        //        _blakButton.titleLabel.font = [UIFont systemFontOfSize:17];
        //        [_blakButton addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
        //         _blakButton.transform = CGAffineTransformMakeRotation (M_PI/90);
        //        _blakButton.transform = CGAffineTransformMakeRotation (M_PI);
//        _blakButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 60, 100)];
//        [_blakButton setImage:[UIImage imageNamed:@"gameReturn"] forState:0];
//        [_blakButton addTarget:self action:@selector(back:) forControlEvents:(UIControlEventTouchUpInside)];
        //        _blakButton.transform = CGAffineTransformMakeRotation (M_PI);
        //
        //        _blakButton.centerX = self.view.centerX;
    }
    return _blakButton;
}
- (void)back:(UIButton*)item {
    if ([_webView canGoBack]) {
        [_webView goBack];
    } else {
        //允许转成横屏
        [self allowRotation:NO];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

#pragma mark 自定义导航按钮支持侧滑手势处理
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    //  [[UIApplication sharedApplication] setStatusBarHidden:YES];
        [self.navigationController setNavigationBarHidden:YES animated:NO]; //设置隐藏

    if (self.navigationController.viewControllers.count > 1) {
        self.delegate = self.navigationController.interactivePopGestureRecognizer.delegate;
        self.navigationController.interactivePopGestureRecognizer.delegate = self;
        
    }
    if (_allowRotation==YES) {
        AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
        appDelegate.allowRotation = YES;//关闭横屏仅允许竖屏
        //允许转成横屏
        [self allowRotation:YES];
    }

}


- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
  
   // [self allowRotation:NO];
 //  [[UIApplication sharedApplication] setStatusBarHidden:NO];
      [self.navigationController setNavigationBarHidden:NO animated:NO]; //设置隐藏
    self.navigationController.interactivePopGestureRecognizer.delegate = self.delegate;

}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    return self.navigationController.viewControllers.count > 1;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return self.navigationController.viewControllers.count > 1;
}
#pragma mark 加载请求
- (void)loadRequest {
    
    if (![self.urlStr hasPrefix:@"http"]) {//是否具有http前缀
        self.urlStr = [NSString stringWithFormat:@"http://%@",self.urlStr];
    }


     [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.urlStr]]];
    
}

#pragma mark WebViewDelegate
- (void)webViewDidStartLoad:(UIWebView *)webView
{
    if(webView == self.webView) {
           [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookieAcceptPolicy:NSHTTPCookieAcceptPolicyAlways];
        
    }
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
  
    webView.hidden = NO;
    // 不加载空白网址
//    if ([request.URL.scheme isEqual:@"about"]) {
//        webView.hidden = YES;
//        return NO;
//    }
    if(webView == self.webView) {
        NSArray *cookies = [NSHTTPCookieStorage sharedHTTPCookieStorage].cookies;
        self.uiWebViewCurrentURL = request.URL;
        YYLog(@"----%@",self.uiWebViewCurrentURL);
        
        if ([request.URL.host isEqualToString:@"m.ls226288.com"]) {
             YYLog(@"-sharedHTTPCookieStorage---%@",cookies);

            NSArray*cookies =[[NSUserDefaults standardUserDefaults]objectForKey:@"cookies"];
            if (cookies.count>0) {
                NSMutableDictionary*cookieProperties = [NSMutableDictionary dictionary];
                [cookieProperties setObject:[cookies objectAtIndex:0]forKey:NSHTTPCookieName];
                [cookieProperties setObject:[cookies objectAtIndex:1]forKey:NSHTTPCookieValue];
                [cookieProperties setObject:[cookies objectAtIndex:3]forKey:NSHTTPCookieDomain];
                [cookieProperties setObject:[cookies objectAtIndex:4]forKey:NSHTTPCookiePath];
                NSHTTPCookie*cookieuser = [NSHTTPCookie cookieWithProperties:cookieProperties];
                [[NSHTTPCookieStorage sharedHTTPCookieStorage]setCookie:cookieuser];
            }
//            NSDictionary *requestHeaderFields = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
//            //设置请求头
//            request.allHTTPHeaderFields = requestHeaderFields;
        //    [_webView loadRequest:request];
            
            
            
        }
        
       
              
              
              
        self.uiWebViewIsLoading = YES;
        [self fakeProgressViewStartLoading];
  
    }
    return YES;
}
#pragma mark - External App Support

- (BOOL)externalAppRequiredToOpenURL:(NSURL *)URL {
    NSSet *validSchemes = [NSSet setWithArray:@[@"http", @"https",@"file"]];
    return ![validSchemes containsObject:URL.scheme];
}

- (void)launchExternalAppWithURL:(NSURL *)URL {
//    self.URLToLaunchWithPermission = URL;
//    if (![self.externalAppPermissionAlertView isVisible]) {
//        [self.externalAppPermissionAlertView show];
//    }
    
}

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    //导航栏配置
    self.navigationItem.title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    [self showLeftBarButtonItem];
    [_refreshControl endRefreshing];
  //  [self stopLoadingAnimation];
    if(webView == self.webView) {
        if(!self.webView.isLoading) {
            self.uiWebViewIsLoading = NO;
            
            [self fakeProgressBarStopLoading];
        }
        
    }
    
    NSArray*nCookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage]cookies];
    NSHTTPCookie*cookie;
    for(id c in nCookies)
    {
        if([c isKindOfClass:[NSHTTPCookie class]])
        {
            cookie=(NSHTTPCookie*)c;
            if([cookie.name isEqualToString:@"PHPSESSID"]) {
                NSNumber*sessionOnly = [NSNumber numberWithBool:cookie.sessionOnly];
                NSNumber*isSecure = [NSNumber numberWithBool:cookie.isSecure];
                NSArray*cookies = [NSArray arrayWithObjects:cookie.name, cookie.value, sessionOnly, cookie.domain, cookie.path, isSecure,nil];
                [[NSUserDefaults standardUserDefaults]setObject:cookies forKey:@"cookies"];
                break;
            }
        }
    }
    
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    webView.hidden = YES;
    if(webView == self.webView) {
        if(!self.webView.isLoading) {
            self.uiWebViewIsLoading = NO;
            
            [self fakeProgressBarStopLoading];
        }

      
    }
  //  [MBProgressHUD hideHUDForView :self.view animated:YES];
}
- (void)after{
// [MBProgressHUD hideHUDForView :self.view animated:YES];
    
}
#pragma mark WKNavigationDelegate

#pragma mark 加载状态回调

//页面开始加载
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation{
    webView.hidden = NO;
    _loadingProgressView.hidden = NO;
    //     [self showLoadingAnimation];
    if ([webView.URL.scheme isEqual:@"about"]) {
        webView.hidden = YES;
    }
}
//JS调用OC
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    NSString * body = message.body;
    //    if ([body isEqualToString:@"onSuccess"]) {
    //
    //        SuccessViewController * SuccessVC = [[SuccessViewController alloc] init];
    //        SuccessVC.title = @"认证失败";
    //        [self.navigationController pushViewController:SuccessVC animated:YES];
    //
    //    }else if ([body isEqualToString:@"onFailure"])
    //    {
    //        FailViewController * failVC = [[FailViewController alloc] init];
    //        failVC.title = @"认证失败";
    //        [self.navigationController pushViewController:failVC animated:YES];
    //    }
    
}
//页面加载完成
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation{
    //导航栏配置
    [webView evaluateJavaScript:@"document.title" completionHandler:^(id _Nullable title, NSError * _Nullable error) {
        self.navigationItem.title = title;
    }];
    
    
    [self stopLoadingAnimation];
    [self showLeftBarButtonItem];
    
    [_refreshControl endRefreshing];
}

-(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    NSString *urlStr = navigationAction.request.URL.absoluteString;
    if ([urlStr hasPrefix:@"alipays://"] || [urlStr hasPrefix:@"alipay://"]) {
        NSURL* alipayURL = [self changeURLSchemeStr:urlStr];
        if (@available(iOS 10.0, *)) {
            [[UIApplication sharedApplication] openURL:alipayURL options:@{UIApplicationOpenURLOptionUniversalLinksOnly: @NO} completionHandler:^(BOOL success) {
                
            }];
        } else {
            // Fallback on earlier versions
            [[UIApplication sharedApplication] openURL:alipayURL];
        }
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}
-(NSURL*)changeURLSchemeStr:(NSString*)urlStr{
    NSString* tmpUrlStr = urlStr.copy;
    if([urlStr containsString:@"fromAppUrlScheme"]) {
        tmpUrlStr = [tmpUrlStr stringByRemovingPercentEncoding];
        NSDictionary* tmpDic = [self dictionaryWithUrlString:tmpUrlStr];
        NSString* tmpValue = [tmpDic valueForKey:@"fromAppUrlScheme"];
        tmpUrlStr = [[tmpUrlStr stringByReplacingOccurrencesOfString:tmpValue withString:@"你对应的URLSchemes"] mutableCopy];
        tmpUrlStr = [[tmpUrlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]] mutableCopy];
    }
    NSURL * newURl = [NSURL URLWithString:tmpUrlStr];
    return newURl;
}
-(NSDictionary*)dictionaryWithUrlString:(NSString*)urlStr{
    if(urlStr && urlStr.length&& [urlStr rangeOfString:@"?"].length==1) {
        NSArray *array = [urlStr componentsSeparatedByString:@"?"];
        if(array && array.count==2) {
            NSString*paramsStr = array[1];
            if(paramsStr.length) {
                NSString* paramterStr = [paramsStr stringByRemovingPercentEncoding];
                NSData *jsonData = [paramterStr dataUsingEncoding:NSUTF8StringEncoding];
                NSDictionary *responseDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:nil];
                return responseDic;
            }
        }
    }
    return nil;
}
//页面加载失败
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error{
    webView.hidden = YES;
}

-(void)dealloc{
    NSHTTPCookie*cookie;
    NSHTTPCookieStorage*storage =[NSHTTPCookieStorage sharedHTTPCookieStorage];for(cookie in[storage cookies]){      [storage deleteCookie:cookie];}

}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
